package com.xiguaji.tiktok.task.awemecomment.spider;

import com.gugee.tiktok.common.model.spider.comment.AwemeCommentResponse;
import com.xiguaji.boot.retry.RetryableException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AwemeCommentSpiderClient {
    @Autowired
    RestTemplate restTemplate;

    @Value("${xiguaji.spider.host}")
    String host;

    @Retryable(value = RetryableException.class, maxAttemptsExpression = "${spider.aweme.comment.retry}")
    public AwemeCommentResponse get(long awemeId, int cursor, int count) {
        String uri = host + "/aweme/CommentList?aweme_id={aweme_id}&cursor={cursor}&count={count}&region=US";
        ResponseEntity<AwemeCommentResponse> responseEntity = restTemplate.getForEntity(uri, AwemeCommentResponse.class, awemeId, cursor, count);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException(String.format("get aweme comment error. status: %s . msg: %s", responseEntity.getStatusCodeValue(), responseEntity.getBody()));
        }
        if (responseEntity.getBody() == null || responseEntity.getBody().getStatus_code() == 3071) {
            throw new RetryableException("get aweme comment error, retry times 20. uri:" +
                    uri.replace("{aweme_id}", String.valueOf(awemeId)).replace("{cursor}", String.valueOf(cursor)).replace("{count}", String.valueOf(count))
            );
        }
        return responseEntity.getBody();
    }
}
